import argparse  # 导入argparse模块，用于处理命令行参数
import time
from concurrent.futures import ThreadPoolExecutor
from urllib.parse import urljoin

from DrissionPage import ChromiumPage
from DrissionPage.errors import *

import business.crawling.guest as guest
import business.pre_crawling.check_chatgpt as check_chatgpt
import business.pre_crawling.load_chatgpt as load_chatgpt
import common.chrome.launcher as chrome_launcher
import lib.utils.log_loader as log_loader
from lib.utils.config_loader import load_config
from lib.utils.redis_util import get_redis_client
from common.data.element_selectors import LISTEN_STATE

logger = log_loader.get_logger()


def initialize_chromium():
    """
    初始化Chromium浏览器实例。

    全局搜索配置文件以获取web应用的URL，确保Chromium加载指定的网页。如果页面不是预期的，或者在加载过程中出现问题，则重新加载页面。

    返回:
        ChromiumPage: 初始化后的页面对象。
    """
    global logger
    # 启动Chromium并创建页面对象
    chrome_launch_config = chrome_launcher.launch_chromium()
    page = ChromiumPage(chrome_launch_config)

    try:
        # 加载应用配置
        app_config = load_config('app.ini')
        load_url = app_config.get('webSite', 'host')
        # 规范化URL，确保它们以尾部斜杠结尾
        normalized_load_url = urljoin(load_url, '/')
        normalized_page_url = urljoin(page.url, '/')

        # 检查当前页面是否为预期的URL，如果不是，则重新加载
        if normalized_load_url != normalized_page_url:
            page.get(load_url, True)
            # 等待页面开始加载
            page.wait.load_start()
        else:
            # 即使URL正确，也检查页面是否正常，以防出现长时间停留或异常
            if check_chatgpt.check_chatgpt_interaction() is False:
                page.get(load_url, True)
                # 等待页面开始加载
                page.wait.load_start()
            else:
                check_page = page.get_tab()
                if check_chatgpt.is_chat_page(check_page) is False:
                    page.get(load_url, True)
                    # 等待页面开始加载
                    page.wait.load_start()

        return page
    except BrowserConnectError:
        # 记录浏览器连接错误并退出
        logger.error("初始化Chromium出错: 浏览器连接失败")
        page.quit()
        exit()
    except Exception as e:
        # 记录其他异常
        logger.error(f"初始化Chromium出错: {e}")
        raise


def main():
    global logger
    start_time = time.time()  # 记录开始时间
    redis_client = get_redis_client()
    redis_client.set(LISTEN_STATE, 1)

    logger.debug("接管chromium-开始")
    page = initialize_chromium()
    logger.debug("环境初始化完成")

    page_tab = page.get_tab()
    page_listening = page.get_tab()
    page_guest = page.get_tab()
    ws_listening = page.get_tab()
    console_listening = page.get_tab()

    # 检查是否进入ChatGPT
    logger.debug("侦测ChatGPT聊天室状态-开始")
    if check_chatgpt.is_chat_page(page_tab) is False:
        ret = load_chatgpt.get_page(page_tab)
        if ret:
            check_chatgpt.save_chatgpt_interaction()
            check_chatgpt.save_new_chat()
            logger.debug("进入ChatGPT成功")

            # 使用ThreadPoolExecutor来管理线程
            with ThreadPoolExecutor() as executor:
                # 启动数据监听线程
                # listen_future = executor.submit(chatgpt_monitors.start_data_listening_tab, page_listening)
                # ws_future = executor.submit(chatgpt_monitors.listening_tab_ws, ws_listening)
                # console_future = executor.submit(chatgpt_monitors.listening_tab_console, console_listening)
                guest_future = executor.submit(guest.text_chat, page_guest)
                try:
                    message_future = executor.submit(guest.get_chat_message, page_guest)
                except Exception as e:
                    logger.error(f"获取消息失败: {e}")
                    message_future = executor.submit(guest.get_chat_message, page_guest)
                # message_future = executor.submit(guest.get_chat_message, page_guest)

            # 不再需要join，因为使用了ThreadPoolExecutor
            # 等待所有线程完成（如果有必要）
            executor.shutdown(wait=True)

        else:
            logger.error("进入ChatGPT失败")
    else:
        check_chatgpt.save_chatgpt_interaction()
        check_chatgpt.save_new_chat()
        # 使用ThreadPoolExecutor来管理线程
        with ThreadPoolExecutor() as executor:
            # 启动数据监听线程
            # listen_future = executor.submit(chatgpt_monitors.start_data_listening_tab, page_listening)
            # ws_future = executor.submit(chatgpt_monitors.listening_tab_ws, ws_listening)
            # console_future = executor.submit(chatgpt_monitors.listening_tab_console, console_listening)
            guest_future = executor.submit(guest.text_chat, page_guest)
            # message_future = executor.submit(guest.get_chat_message, page_guest)
            try:
                message_future = executor.submit(guest.get_chat_message, page_guest)
            except Exception as e:
                # 检查是否停止监听
                listen_state = redis_client.get(LISTEN_STATE)
                if listen_state and listen_state.isdigit() and int(listen_state) == 0:
                    logger.debug('监听已停止')
                else:
                    logger.error(f"获取消息失败: {e}")
                message_future = executor.submit(guest.get_chat_message, page_guest)

        # 不再需要join，因为使用了ThreadPoolExecutor
        # 等待所有线程完成（如果有必要）
        executor.shutdown(wait=True)

    # check_chatgpt.get_tab_info(page_listening)

    # 计算执行时间
    end_time = time.time()  # 记录结束时间
    execution_time = end_time - start_time  # 计算执行时间，从开始加载页面到页面开始加载的时间
    logger.debug(f"应用运行时长: {execution_time} 秒")


if __name__ == '__main__':
    # 定义命令行参数
    # 初始化命令行参数解析器
    parser = argparse.ArgumentParser(description='ChatGPT转发端')

    # 添加运行模式参数
    parser.add_argument('--mode', type=str, default='menu', help='指定运行模式，默认chatgpt3.5匿名模式')

    # 处理命令行参数
    args = parser.parse_args()

    # 获取运行模式参数
    running_mode = args.mode
    if running_mode == 'PROD':
        print('模式占位符')
    else:  # DEV 环境
        main()
